from PyQt5.QtCore import Qt

from logger import logger
from context import Component
from PyQt5.QtWidgets import QWidget, QFileDialog, QVBoxLayout
from PyQt5.QtGui import QColor
from qgis.gui import (
    QgsMapCanvas
)
from .tree import Tree
from .status import Status
from .route import Route
from .layer import Layer
from PyQt5.QtCore import pyqtSignal

@Component("map")
class Map(QWidget):
    tree_toggled = pyqtSignal(bool)
    
    """极地海图主应用程序类"""
    def __init__(self):
        super(Map, self).__init__()
        logger.info("创建地图组件")
        self.canvas = None
        self.layer = None
        self.route = None
        self.tree = None
        self.status = None

    def init_ui(self, parent=None):
        """初始化UI，必须在QApplication创建后调用"""
        self.canvas = QgsMapCanvas()
        self.canvas.setObjectName("map_canvas")
        self.canvas.setCanvasColor(QColor("white")) 

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 设置左、上、右、下边距为0
        layout.setSpacing(0)  # 设置控件之间的间距为0
        layout.addWidget(self.canvas)
        self.setLayout(layout)
        self.setStyleSheet("border: none;")  # 去掉外层Widget的边框

        self.tree = Tree(parent.treeDock,self.tree_toggled)

        # 操作状态
        self.status = Status(self.canvas)
        parent.setStatusBar(self.status.get())

        # 地图加载
        self.layer = Layer(self.canvas)
        self.layer.map_loaded.connect(self.status.show_gps)

        # 绘制航线
        self.route = Route(self.canvas)

        logger.info("地图组件初始化完成")

    def open_file(self):
        self.layer.open_file()

    def start_drawing(self):
        self.route.start_drawing()

    def exit_drawing(self):
        self.route.exit_drawing()

    def save_route(self):
        self.route.save_route()

    def clear_route(self):
        self.route.clear_route()

    def toggle_layer(self):
        self.tree.toggle_layer()
    def add_ship_route(self):
        self.route.add_ship_route()
    def clear_ship_route(self):
        self.route.clear_ship_route()
    def show_ship_track(self):
        self.route.show_ship_track()
